# 读取配置文件
import json
import modules
import numpy
from tkinter import messagebox
import tkinter as tk

config = {}

def get_config():
    global config
    return config

def load_config():
    global config
    with open("./data/.config/config.json", "r") as f:
        config = json.load(f)

        if config.get("servo_names") is None:
            config["servos"] = ["There is no servo in config.json"]

        if config.get("servo_colum_num") is None:
            config["servo_colum_num"] = 10

    for each in config["servo_names"]:
        modules.servo(each)

    return config

def save_config():
    with open("./data/.config/config.json", "w") as f:
        global config
        json.dump(config, f, indent=4)

def get_action_keys():
    global config
    action_keys = []

    servo_num = modules.servos.__len__()

    if config.get("action_keys") is None:
        action_keys = [modules.action_key(numpy.zeros(servo_num), 1000)]
        return action_keys

    else:
        for each in config["action_keys"]:

            if each.get("angles") is None or each.get("time") is None:
                action_keys = [modules.action_key(numpy.zeros(servo_num), 1000)]
                return action_keys


            if each.get("angles").__len__() != servo_num:
                action_keys = [modules.action_key(numpy.zeros(servo_num), 1000)]
                config["action_keys"] = []
                return action_keys

            action_keys.append(modules.action_key(each["angles"], each["time"]))

        return action_keys

# 将action_key_list添加到config
def action_key_set_to_default(action_key_list:list):
    action_key_list_ = action_key_list_to_config_format(action_key_list)
    config.update({"action_keys": action_key_list_})

def action_key_list_to_config_format(action_key_list:list):
    key_list = []

    for action_key in action_key_list:
        angles = [int(angle) for angle in action_key.angles]
        time = int(action_key.time)
        key_list.append({
            "angles": angles,
            "time": time
        })

    return key_list

def action_add(action_name:str, action_keys:list):
    # 判读新的名字是否已经存在了
    if action_name in config["action_names"]:
        is_continue = messagebox.askyesno("注意", "改名字已经存在, 继续保存将会将原来的覆盖")
        if not is_continue:
            return

    else :
        config["action_names"].append(action_name)

    # 将list装为json并保存
    action_keys_json = action_key_list_to_config_format(action_keys)
    with open(f"./data/action_{action_name}.json", 'w', -1) as f:
        json.dump(action_keys_json, f, indent=4)

    messagebox.showinfo("成功", "保存成功")

def action_load(action_name:str):
    """
    加载action_name对应的action_key
    :param action_name:
    :return:action_key_list
    """
    # 判读是否在列表中
    if action_name not in config["action_names"]:
        messagebox.showerror("错误", "没有找到该动作")
        return
    
    with open(f"./data/action_{action_name}.json", 'r') as f:
        try:
            action_keys_json = json.load(f)
            action_keys = []
            for each in action_keys_json:
                angles = each["angles"]
                time = each["time"]
                action_keys.append(modules.action_key(angles, time))
        except:
            messagebox.showerror("错误", "加载失败")
            # 将名字从列表中删除
            config["action_names"].remove(action_name)
            return None

        messagebox.showinfo("成功", "加载成功")
        return action_keys
def action_delete(action_name:str):
    """
    删除action_name对应的action_key
    :param action_name:
    :return:
    """

    if action_name not in config["action_names"]:
        messagebox.showerror("错误", "没有找到该动作")
        return

    config["action_names"].remove(action_name)
    messagebox.showinfo("成功", "删除成功")
    

def get_action_names():
    return config.get("action_names")

def save(path, config:dict):
    with open(path, "w") as f:
        json.dump(config, f, indent=4)